import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 邹陆川
 * @Date: 2022/04/19/9:01 上午
 * @Description:基于数组实现队列
 */
public class QueueByArray<T> implements Iterable<T>{
  //定义一个变量存储数据长度
  private int N;
  //定义一个数组
  private T[] arr;

  public QueueByArray(int initialCapacity) {
    //初始化数组
   arr = (T[]) new Object[initialCapacity];
  }
  //是否为空
  public boolean isEmpty(){
    return this.N == 0;
  }
  //获得当前队列元素个数
  public int size(){
    return this.N;
  }
  //往队列插入一个元素
  public void enqueue(T t){
    if(this.N+1 > arr.length){
      //扩容
      resize((int) (this.N*2));
    }
    //往数组N处插入数据
    arr[this.N] = t;
    this.N ++;
  }
  //往队列取出一个元素
  public T dequeue(){
    //从数组0处取出数据
    T t = arr[0];
    //让后面的值往前面覆盖
    for (int i = 0; i < this.N-1; i++) {
      arr[i] = arr[i+1];
    }
    this.N --;
    //降容
    if (N<arr.length/4){
      resize(arr.length/2);
    }

    return t;
  }
  //扩容/降容机制
  public void resize(int newSize){
    //定义一个临时数组
    T[] temp = arr;
    //定义一个新数组
    arr =(T[]) new Object[newSize];
    //将临时数组存到新数组中
    for (int i = 0; i < this.N; i++) {
      arr[i] = temp[i];
    }
  }

  @Override
  public Iterator<T> iterator() {
    return new myIterator();
  }
  private class myIterator implements Iterator{
    private int len = N;
    @Override
    public boolean hasNext() {
      return len-- > 0;
    }

    @Override
    public Object next() {
      //遍历要从0开始
      return arr[N-(len+1)];
    }
  }
}
